package com.xiaoluo.lottery.dao;

import com.xiaoluo.lottery.entity.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by Administrator on 2016/4/5.
 */
@Component
public class PlayerJdbcDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private static final Logger log= LoggerFactory.getLogger(PlayerJdbcDao.class);
    private RowMapper<Player> rowMapper=new RowMapper<Player>() {
        @Override
        public Player mapRow(ResultSet resultSet, int i) throws SQLException {
            Player player=new Player();
            player.setOpenId(resultSet.getString("open_id"));
            player.setBalance(resultSet.getDouble("balance"));
            player.setCreateAt(resultSet.getTimestamp("create_at"));
            player.setNickName(resultSet.getString("nick_name"));
            player.setUpdateAt(resultSet.getTimestamp("update_at"));
            player.setHeadImage(resultSet.getString("head_image"));
            return player;
        }
    };
    public Player getPlayer(String openId){
        String sql="SELECT * FROM lottery_player where open_id='"+openId+"'";
        try{
            return jdbcTemplate.queryForObject(sql,rowMapper);
        }catch (EmptyResultDataAccessException e){
            log.error("Get empty player:openId={}",openId);
            e.printStackTrace();
            return null;
        }
    }
    public int createPlayer(Player player){
        String sql="INSERT INTO lottery_player (open_id,balance,create_at,nick_name,update_at,head_image) VALUES (?,?,?,?,?,?,?)";
        Object[] params=new Object[]{
          player.getOpenId(),player.getBalance(),player.getCreateAt()
                ,player.getNickName(),player.getUpdateAt(),player.getHeadImage()
        };
        int i=jdbcTemplate.update(sql,params);
        return i;
    }
    public int updatePlayer(Player player){
        String sql="UPDATE lottery_player set balance=?,nick_name=?,update_at=?,head_image=? where open_id=?";
        Object[] params=new Object[]{
          player.getBalance(),player.getNickName(),player.getUpdateAt(),player.getHeadImage(),player.getOpenId()
        };
        return jdbcTemplate.update(sql,params);
    }
    public int updateBalance(String openId,double amount){
        String sql="UPDATE lottery_player set balance=(balance+"+amount+") where open_id='"+openId+"'";
        return jdbcTemplate.update(sql);

    }
}
